﻿using B.S.DataBase.MyProject.Domain.患者移动端;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using MediatR;
<<<<<<<< HEAD:MedicalPCTerminal.Read.API/Appcation/CommandHandlers/PatientMovementCommandHandler/LoginCommandHandler.cs
using MedicalPCTerminal.Read.API.Appcation.Commands.PatientMovementCommand;

namespace MedicalPCTerminal.Read.API.Appcation.CommandHandlers.PatientMovementCommandHandler
========
using MedicalPCTerminal.Read.API.Appcation.Commands.患者移动端;

namespace MedicalPCTerminal.Read.API.Appcation.CommandHandlers.患者移动端
>>>>>>>> parent of fe317f5 (修改命名空间):MedicalPCTerminal.Read.API/Appcation/CommandHandlers/患者移动端/LoginCommandHandler.cs
{
    /// <summary>
    /// 处理登陆命令
    /// </summary>
    public class LoginCommandHandler : IRequestHandler<LoginCommand, APIResult<Me>>
    {
        private readonly SqlSugarContext sqlSugar;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="meRepository">仓储</param>
        public LoginCommandHandler(SqlSugarContext sqlSugar)
        {
            this.sqlSugar = sqlSugar;
        }
        public async Task<APIResult<Me>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<List<Me>> result = new APIResult<List<Me>>();
                var entity=sqlSugar.db.Queryable<Me>().Where(x=>x.UserName==request.UserName&&x.Password==request.Password).ToList();
                if (entity != null)
                {
                    result.Code = APIEnum.登录成功;
                    result.Msg = APIEnum.登录成功.ToString();
                    entity.Img = CreateTokenString();
                    result.data = entity;
                }
                else
                {
                    result.Code = APIEnum.登录失败密码或用户名错误;
                    result.Msg = APIEnum.登录失败密码或用户名错误.ToString();
                }
                return await Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }

        }

        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <returns></returns>
        private string CreateTokenString()
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
